package com.xiang.WebSocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Service;

import com.xiang.api.Util;
import com.xiang.api.entity.Message;
import com.xiang.sql.entity.Msg;

@Service
public class WebSocketService {
  private final CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
  private final AtomicInteger onlineCount = new AtomicInteger(0);

  public void addWebSocket(MyWebSocket socket) {
    if (webSocketSet.add(socket)) {
      onlineCount.getAndIncrement(); // 在线数+1
    }
  }

  public void removeWebSocket(MyWebSocket socket) {
    if (webSocketSet.remove(socket)) {
      onlineCount.getAndDecrement(); // 在线数-1
    }
  }

  public void sendTarget(Msg msg) {
    for (MyWebSocket socket : webSocketSet) {
      if (socket.user != null && socket.user.id.equals(msg.target)) {
        // socket.send(new Message(msg, "msgRecv"));
        try {
          socket.session.getBasicRemote().sendText(Util.toJString(new Message(msg, "msgRecv")));
        } catch (IOException e) {
        }
      }
    }
  }

  public void sendTarget(String msg, String target) {
    if (target != null && msg != null) {
      for (MyWebSocket socket : webSocketSet) {
        if (socket.user != null && socket.user.id.equals(target)) {
          // socket.send(new Message(msg, true));
          try {
            socket.session.getBasicRemote().sendText(Util.toJString(new Message(msg, true)));
          } catch (IOException e) {
          }
        }
      }
    }
  }

  public void sendTarget(String msg, String target, String type) {
    if (target != null && msg != null) {
      for (MyWebSocket socket : webSocketSet) {
        if (socket.user != null && socket.user.id.equals(target)) {
          try {
            socket.session.getBasicRemote().sendText(Util.toJString(new Message(msg, type)));
          } catch (IOException e) {
          }
        }
      }
    }
  }

  public void sendTarget(Message data) {
    for (MyWebSocket socket : webSocketSet) {
      if (socket.user != null && socket.user.id.equals(data.sid)) {
        try {
          socket.session.getBasicRemote().sendText(Util.toJString(data));
        } catch (IOException e) {
        }
      }
    }
  }
}
